import {
  Button,
  Col,
  Layout,
  message,
  Row,
  Table,
  Tooltip,
  Typography,
} from "antd";
import { DownloadOutlined } from "@ant-design/icons";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { getBidsForTender } from "../../api/tendering/tenderApi";
import {
  downloadElectricalSummaryFile,
  createElectricalSummary,
  fetchElectricalSummaryFile,
} from "../../api/tendering/summaryApi";
import { createElectricalBidForTender } from "../../api/tendering/uploadApi";
import * as XLSX from "xlsx";
import BidRecordList from "../../components/BidRecordList/BidRecordList";
import type { BidRecord } from "../../components/BidRecordList/schema";
import type { BidInfo, TendersBidsGETResponse } from "../../types/api";
import FileUploader from "../../components/FileUploader/FileUploader";

const { Content } = Layout;
const { Title } = Typography;

interface ExcelRow {
  key: number;
  [key: string]: string | number;
}
type Stage = "idle" | "loading" | "summary" | "error";

const SummaryForElectricalFitting: React.FC = () => {
  const { tableId } = useParams<{ tableId: string }>();
  const navigate = useNavigate();
  const [bidRecords, setBidRecords] = useState<BidRecord[]>([]);
  const [uploading, setUploading] = useState(false);
  const [excelData, setExcelData] = useState<ExcelRow[]>([]);
  const [excelColumns, setExcelColumns] = useState<object[]>([]);
  const [currentStage, setCurrentStage] = useState<Stage>("idle");

  async function fetchBidRecords(): Promise<void> {
    if (!tableId) return;
    try {
      const records: TendersBidsGETResponse = await getBidsForTender(tableId);
      setBidRecords(
        records.bids.map(
          (bid: BidInfo): BidRecord => ({
            id: bid.id,
            name: bid.name,
            has_bargaining: bid.has_bargaining,
          })
        )
      );
    } catch (err) {
      message.error("加载投标记录失败，请稍后重试。");
      console.error(err);
    }
  }
  useEffect(() => {
    fetchBidRecords();
  }, [tableId]);

  useEffect(() => {
    if (!uploading) {
      fetchBidRecords();
    }
  }, [uploading]); // 只依赖 uploading

  async function fetchAndParseSummary(): Promise<void> {
    try {
      const file = await fetchElectricalSummaryFile(tableId!);
      const arrayBuffer = await file.blob.arrayBuffer();
      const workbook = XLSX.read(arrayBuffer, { type: "array" });
      const sheetName: string = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[sheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet, {
        header: 1,
        defval: "",
      }) as string[][];

      // 限制最多读取50行
      const limitedJsonData = jsonData.slice(0, 500);

      if (limitedJsonData.length >= 2) {
        // 1.产品信息部分
        const productHeaders: string[] = [
          "序号",
          "产品名称",
          "规格型号",
          "单位",
          "理论重量",
          "要求品牌",
        ];
        const columns = productHeaders.map((title, idx) => ({
          title,
          dataIndex: `col${idx}`,
          key: `col${idx}`,
          width: 120,
          align: "center",
          render: (text: string) => (
            <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
              {text}
            </div>
          ),
        }));

        // 2.报价部分和最低价部分
        const groupRow = limitedJsonData[0]; // 第一行：供应商名/最低价/空
        const titleRow = limitedJsonData[1]; // 第二行：子表头
        let colIdx = productHeaders.length;

        // 2.1供应商报价部分
        while (colIdx < groupRow.length && groupRow[colIdx]) {
          const supplier = groupRow[colIdx];
          let children: object[] = [];
          let start = colIdx;

          // 判断该供应商有几个子表头
          while (colIdx < titleRow.length && !groupRow[colIdx + 1]) {
            children.push({
              title: titleRow[colIdx],
              dataIndex: `${supplier}_${titleRow[colIdx]}`,
              key: `${supplier}_${titleRow[colIdx]}`,
              width: 120,
              align: "center",
              render: (text: string) => (
                <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                  {text}
                </div>
              ),
            });
            colIdx++;
          }

          // 最后一个子表头
          children.push({
            title: titleRow[colIdx],
            dataIndex: `${supplier}_${titleRow[colIdx]}`,
            key: `${supplier}_${titleRow[colIdx]}`,
            width: 120,
            align: "center",
            render: (text: string) => (
              <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                {text}
              </div>
            ),
          });
          columns.push({
            title: supplier,
            children,
          });
          colIdx++;
        }

        // 2.2跳过空白分隔列
        while (colIdx < groupRow.length && !groupRow[colIdx]) {
          colIdx++;
        }

        // 2.3最低价部分
        while (colIdx < groupRow.length && groupRow[colIdx]) {
          columns.push({
            title: groupRow[colIdx],
            dataIndex: `minprice_${groupRow[colIdx]}`,
            key: `minprice_${groupRow[colIdx]}`,
            width: 120,
            align: "center",
            render: (text: string) => (
              <div style={{ whiteSpace: "pre-wrap", wordBreak: "break-all" }}>
                {text}
              </div>
            ),
          });
          colIdx++;
        }

        // 3.数据部分
        const dataSource: ExcelRow[] = [];
        let lastProductName = "";

        // 从第3行开始（索引2），最多到第100行
        for (let rowIdx = 2; rowIdx < limitedJsonData.length; rowIdx++) {
          const row = limitedJsonData[rowIdx];
          const obj: ExcelRow = { key: rowIdx - 2 };

          // 序号列：用idx递增
          obj["col0"] = rowIdx - 1;

          // 产品名称合并单元格处理
          if (row[1]) {
            lastProductName = row[1];
            obj["col1"] = row[1];
          } else {
            obj["col1"] = lastProductName;
          }

          // 规格型号为空，说明产品分组结束（但这里依然要填充）
          obj["col2"] = row[2] || "";
          obj["col3"] = row[3] || "";
          obj["col4"] = row[4] || "";
          obj["col5"] = row[5] || "";

          // 供应商报价部分
          let colIdx2 = productHeaders.length;

          // 供应商分组
          while (colIdx2 < groupRow.length && groupRow[colIdx2]) {
            const supplier = groupRow[colIdx2];
            let start = colIdx2;

            while (colIdx2 < titleRow.length && !groupRow[colIdx2 + 1]) {
              obj[`${supplier}_${titleRow[colIdx2]}`] = row[colIdx2];
              colIdx2++;
            }
            obj[`${supplier}_${titleRow[colIdx2]}`] = row[colIdx2];
            colIdx2++;
          }

          // 跳过空白分隔列
          while (colIdx2 < groupRow.length && !groupRow[colIdx2]) {
            colIdx2++;
          }

          // 最低价部分
          while (colIdx2 < groupRow.length && groupRow[colIdx2]) {
            obj[`minprice_${groupRow[colIdx2]}`] = row[colIdx2];
            colIdx2++;
          }

          dataSource.push(obj);
        }

        setExcelColumns(columns);
        setExcelData(dataSource);
      } else {
        setExcelColumns([]);
        setExcelData([]);
      }
    } catch (err) {
      message.error("解析汇总文件失败");
      console.error(err);
    }
  }

  async function handleBidUpload(file: File): Promise<void> {
    if (!tableId) return;
    setUploading(true);
    try {
      await createElectricalBidForTender(tableId, file);
      message.success(`文件 ${file.name} 上传成功`);
      await fetchBidRecords();
    } catch (err) {
      message.error(`文件 ${file.name} 上传失败，请稍后重试`);
      console.error(err);
    } finally {
      setUploading(false);
    }
  }

  async function onUploading(loading: boolean) {
    setUploading(loading);
  }

  async function handleSummary() {
    if (!tableId) return;

    setUploading(true);
    try {
      await createElectricalSummary(tableId);
      message.success("议价汇总表生成成功");
      setCurrentStage("summary");
      await fetchAndParseSummary();
    } catch (err: any) {
      message.error(`议价汇总表生成失败：${err.message || "未知错误"}`);
      console.error(err);
    } finally {
      setUploading(false);
    }
  }

  async function handleDownload() {
    if (!tableId) return;

    setUploading(true);
    try {
      await downloadElectricalSummaryFile(tableId);
      message.success("议价汇总表下载成功");
    } catch (err: any) {
      message.error(`议价汇总表下载失败：${err.message || "未知错误"}`);
      console.error(err);
    } finally {
      setUploading(false);
    }
  }

  return (
    <Layout style={{ height: "90vh", width: "96vw" }}>
      <Content style={{ height: "100%", width: "100%", display: "flex" }}>
        <Row
          gutter={[0, 0]}
          style={{
            height: "100%",
            width: "100%",
            display: "flex",
            flexWrap: "nowrap",
          }}
        >
          {/* 左侧上传区域 */}
          <Col
            span={8}
            style={{
              border: "16px",
              boxSizing: "border-box",
              background: "#fff",
              marginRight: 8,
              minWidth: "320px",
              height: "100%",
              position: "sticky",
              overflow: "hidden",
              zIndex: 2,
              display: "flex",
              flexDirection: "column",
              padding: "0 16px 0 16px",
            }}
          >
            <div
              style={{
                padding: "8px",
                display: "flex",
                flexDirection: "column",
                height: "100%",
                width: "100%",
                overflow: "hidden",
              }}
            >
              <Button
                style={{ marginBottom: 16, width: "110px" }}
                onClick={() => navigate(-1)}
              >
                返回上一页
              </Button>

              <FileUploader
                title="电气材料招标文件上传"
                onUpload={handleBidUpload}
                onUploading={onUploading}
              />
              <BidRecordList
                bidRecords={bidRecords}
                onUploading={(isUploading: boolean): void => {
                  setUploading(isUploading);
                }}
              />
              <div
                style={{
                  marginTop: "auto",
                  padding: "16px 0 8px",
                  display: "flex",
                  justifyContent: "flex-end",
                }}
              >
                <Tooltip
                  title="将已上传的招标进行汇总并生成Excel汇总表"
                  placement="left"
                  mouseEnterDelay={0.5}
                >
                  <Button
                    type="primary"
                    onClick={handleSummary}
                    loading={uploading}
                    style={{ marginRight: "16px" }}
                  >
                    {uploading ? "生成中..." : "生成议价汇总表"}
                  </Button>
                </Tooltip>
              </div>
            </div>
          </Col>

          {/* 右侧预览区域 */}
          <Col
            span={16}
            style={{
              border: "16px",
              height: "100%",
              overflow: "hidden",
              flex: "1 1 0%",
            }}
          >
            <div
              style={{
                display: "flex",
                flexDirection: "column",
                height: "100%",
                width: "100%",
                border: "16px",
                boxSizing: "border-box",
                background: "#fff",
                padding: "16px",
                overflow: "hidden",
              }}
            >
              {excelColumns.length === 0 ? (
                <div
                  style={{
                    color: "#faad14",
                    fontWeight: 500,
                    fontSize: 18,
                    textAlign: "center",
                    marginTop: 40,
                  }}
                >
                  暂无汇总数据，请先上传文件或点击"汇总"按钮生成。
                </div>
              ) : (
                <>
                  <div style={{ margin: 8 }}>
                    <Title level={4}>汇总报告</Title>
                    {currentStage === "summary" ? (
                      <div
                        style={{
                          background: "#f6ffed",
                          padding: 8,
                          borderRadius: 4,
                          whiteSpace: "pre-wrap",
                          maxHeight: 120,
                          overflowY: "auto",
                        }}
                      ></div>
                    ) : null}
                  </div>
                  {/* 数据预览 + 下载按钮 */}
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      margin: "8px 8px 0 8px",
                    }}
                  >
                    <Title level={5} style={{ margin: 0 }}>
                      数据预览
                    </Title>
                    <Button
                      icon={<DownloadOutlined />}
                      onClick={handleDownload}
                      type="primary"
                    >
                      下载
                    </Button>
                  </div>

                  <div
                    style={{
                      flex: 1,
                      minHeight: 0,
                      marginTop: "10px",
                    }}
                  >
                    <Table
                      dataSource={excelData}
                      columns={excelColumns}
                      pagination={false}
                      rowKey={(row) => row.key}
                      bordered={true}
                      scroll={{
                        x: "max-content",
                        y: "400px", // calc(96vh - 280px)
                      }}
                      style={{ width: "100%", height: "100%" }}
                      title={() => null}
                      size={"middle"}
                    />
                  </div>
                </>
              )}
            </div>
          </Col>
        </Row>
      </Content>
    </Layout>
  );
};

export default SummaryForElectricalFitting;
